<template>
  <a-row :gutter="10">
    <a-col :span="24">
      <div class="ai-chat-container">
        <div class="chat-history">
          <div v-for="(msg, index) in history" :key="index">
            <div class="chat-box">
              <div :class="['message', msg.role]">
                <p class="message-think" v-if="msg.think">{{ msg.think }}</p>
                <p class="message-think" v-if="!(msg.content || msg.think)">{{ msg.loadText }}</p>
                <p>{{ msg.content }}</p>
              </div>
            </div>
          </div>
        </div>

        <div class="input-section">
          <a-input
            v-model:value="inputText"
            placeholder="输入你的问题..."
            @pressEnter="handleSend"
          >
            <template #suffix>
              <a-button type="primary" @click="handleSend">
                发送
              </a-button>
            </template>
          </a-input>

          <!--<div class="extra-controls">-->
          <!--	<voice-input @transcript="handleSend" />-->
          <!--	<ppt-upload @processed="handlePPTResponse" />-->
          <!--</div>-->
        </div>
      </div>
	</a-col>
  </a-row>
</template>

<script setup>
// 整合所有功能
import {ref} from 'vue';
import chatApi from '@/api/chat/chatApi'

const history = ref([
  {role: 'user', content: '你好'},
  {role: 'assistant', content: '你好，这里是测试机器人'}
]);
const inputText = ref('');

const isThink = ref(false)
const endedNormally = ref(false)

const handleSend = async () => {
  const text = inputText.value
  history.value.push({role: 'user', content: text});
	history.value.push({role: 'assistant', think: '', content: '', loadText: '正在深度思考......'});
  	const response = await fetchAIResponse(text);
	inputText.value = '';
};

async function fetchAIResponse(text) {

	const eventSource = new EventSource(`http://localhost:3001/chat/postChat?message=${text}`);
  const isThink2 = false;
	eventSource.onmessage = (event) => {
		console.log('收到数据:', event.data);
    if (event.data.includes('[DONE]') || event.data.includes('[END]')) { // 检测结束标记
      console.log('结束标记已收到！！！！！！！！！！ ==================== ',event.data);
      eventSource.close();
      return;
    }
		if(event.data.includes('<think>')) {
			isThink.value = true;
		} else if(event.data.includes('</think>')) {
			nextTick(() => {
				isThink.value = false;
			});
		}
		if(isThink.value) {
			history.value[history.value.length - 1].think += event.data;
		} else {
			history.value[history.value.length - 1].content += event.data;
		}

	};

	eventSource.addEventListener('end', () => {
		console.log('流式传输结束');
    endedNormally.value = true;
		setTimeout(() => {
      console.log('关闭连接')
      eventSource.close();
		}, 3000);
	});

	eventSource.addEventListener('error', (err) => {
		console.error('发生错误:', err, endedNormally.value);
    if(endedNormally.value) {
      endedNormally.value = false;
      return;
    }
		eventSource.close();
		history.value.push({role: 'assistant', content: "发生错误，请重新提问"});
	});
}

async function getChat(text) {
	const params = {
		messages: [
			{role: 'system', content: text}
		]
	}
	chatApi.sendChat(params).then((res) => {
		console.log('返回数据 -', res)
	})
}
</script>

<style lang="less" scoped>
.ai-chat-container {
  display: block;
  max-width: 90%;
  margin: 0 auto;
  padding: 20px;
  min-height: 100vh;
  background-color: #cce5a6;
}
.chat-box {
  display: flex;
  .message {
    justify-content: flex-start;
    .message-think {
      color: #999;
    }
  }
  .user {
    flex-direction: row-reverse;
  }
}
.message {
  display: inline-block;
  padding: 12px;
  margin: 8px 0;
  border-radius: 8px;
  max-width: 80%;
	white-space: normal;
}

.message.user {
  background: #f0f7ff;
  margin-left: auto;
  text-align: left;
}

.message.assistant {
  background: #f5f5f5;
}

.input-section {
  bottom: 20px;
  width: 100%;
  max-width: 800px;
}

.extra-controls {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}
</style>
